package cn.tjad.tjad2.module.plan.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.fragment.BaseFragment;
import com.qiandian.android.base.widget.TJADTTitleView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.OnClick;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.LoginBean;
import cn.tjad.tjad2.data.bean.PlanTask;
import cn.tjad.tjad2.data.bean.Task;
import cn.tjad.tjad2.data.bean.User;
import cn.tjad.tjad2.data.event.PlanTaskEditEvent;
import cn.tjad.tjad2.net.http.ResponseObserver;
import cn.tjad.tjad2.net.http.RetrofitManager;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.RxUtils;
import cn.tjad.tjad2.utils.Tools;

@Route(path = PageId.PLAN_TASK_DETAIL)
public class PlanTaskDetailFragment extends BaseFragment implements OnRefreshListener {

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.task_name)
    TextView taskNameTV;
    @BindView(R.id.plan_duration)
    TextView planDurationTV;
    @BindView(R.id.plan_start_time)
    TextView planStartTimeTV;
    @BindView(R.id.plan_end_time)
    TextView planEndTimeTV;
    @BindView(R.id.actual_duration)
    TextView actualDurationTV;
    @BindView(R.id.actual_start_time)
    TextView actualStartTimeTV;
    @BindView(R.id.actual_end_time)
    TextView actualEndTimeTV;
    @BindView(R.id.task_status)
    TextView taskStatusTV;
    @BindView(R.id.task_delay)
    TextView taskDelayTV;
    @BindView(R.id.related_component)
    TextView taskRelatedTV;
    @BindView(R.id.task_manager)
    TextView taskManagerTV;
    @BindView(R.id.task_edit_btn)
    Button editBtn;

    private Task task;
    private PlanTask planTask;
    private boolean shouldRefresh;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View getContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.plan_task_detail, null);
    }

    @Override
    protected void setCustomerTitle(TJADTTitleView titleView) {
        super.setCustomerTitle(titleView);
        titleView.setCenterText("任务详情");
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            task = (Task) bundle.getSerializable(Keys.TASK_ITEM);
            planTask = (PlanTask) bundle.getSerializable(Keys.PLAN_TASK);
            if (task != null) {
                fillData(task);
            }
        }
        refreshLayout.setOnRefreshListener(this);
    }

    private void fillData(Task task) {
        taskNameTV.setText(task.name);
        planStartTimeTV.setText(task.planStartTime);
        planEndTimeTV.setText(task.planEndTime);
        int planDuration = task.planDay;
        if (planDuration != -1) {
            planDurationTV.setText(planDuration + "");
        } else {
            planDurationTV.setText("");
        }
        actualStartTimeTV.setText(task.actualStartTime);
        actualEndTimeTV.setText(task.actualEndTime);
        int actualDuration = task.actualDay;
        if (actualDuration != -1) {
            actualDurationTV.setText(actualDuration + "");
        } else {
            actualDurationTV.setText("");
        }
        taskStatusTV.setText(Tools.getTaskStatus(task.status));
        if (task.delay) {
            taskDelayTV.setText("已滞后");
        } else {
            taskDelayTV.setText("未滞后");
        }
        if (task.children != null && task.children.size() > 0) {
            taskRelatedTV.setText("已关联");
        } else {
            taskRelatedTV.setText("未关联");
        }
        if (task.user != null) {
            taskManagerTV.setText(task.user.name);
        } else {
            taskManagerTV.setText("");
        }
        LoginBean loginInfo = TjadApplication.getInstance().getSession().getLoginInfo();
        User createUser = planTask.createUser;
        User responseUser = task.user;
        if (loginInfo.admin || (createUser != null && loginInfo.id == createUser.id) || (responseUser != null && loginInfo.id == createUser.id)) {
            editBtn.setVisibility(View.VISIBLE);
        } else {
            editBtn.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.task_edit_btn)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.task_edit_btn:
                    Bundle args = new Bundle();
                    args.putSerializable(Keys.TASK_ITEM, task);
                    args.putString(Keys.TITLE, task.name);
                    RouteUtils.toFragmentActivity(getContext(), PageId.PLAN_TASK_EDIT, args);
                break;
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        RetrofitManager.getInstance()
                .getApiService()
                .getTaskDetail(Tools.getProjectId(), planTask.id, task.id)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<Task>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<Task> t) {
                        fillData(t.result);
                        refreshLayout.finishRefresh(true);
                    }

                    @Override
                    public void onFailed(String message) {
                        Tools.showToast(message);
                        refreshLayout.finishRefresh(false);
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (shouldRefresh) {
            refreshLayout.autoRefresh();
            shouldRefresh = false;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEvent(PlanTaskEditEvent event) {
        this.shouldRefresh = true;
    }

}
